<template>
  <div style="width: 100%;height: 100%;">
    <BaseMainSlot :show-tab="true">
      <template v-slot:search-box>
        <SearchForm :form-config="formConfig" :form-data="filterData" @search="search" />
      </template>
      <template v-slot:btn-box>
        <div class="page-top__todo">
          <CommonBtn @click="reload">刷新</CommonBtn>
          <CommonBtn @click="addEditShow = true">添加</CommonBtn>
          <CommonBtn :disabled="!delActive" @click="del">删除</CommonBtn>
        </div>
      </template>
      <template v-slot:table-box>
        <tdtable v-loading="tableLoading" :prop-list="[]" :page="page" :table-data="tableData" :show-index-column="true" :show-select-column="true" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange" @handleSelectionChange="handleSelectionChange">
          <el-table-column prop="productionInventoryNo" :label="productionInventoryNoLabel" />
          <el-table-column prop="generationTime" label="创建时间" />
          <el-table-column prop="productName" label="加工产品" />
          <el-table-column prop="batchNo" label="所属批次号" />
          <el-table-column prop="taskName" label="所属工单" />
          <el-table-column prop="orderNo" :label="orderNoLabel" />
          <el-table-column label="当前状态" width="100">
            <template slot-scope="scope">
              <span :class="scope.row.status">{{ statusMap[scope.row.status] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template v-if="scope.row.productionInventoryNo" slot-scope="scope">
              <el-button type="text" class="text-btn-cursor" size="small" @click="edit(scope.row, 'detail')">查看详情</el-button>
              <el-button v-if="['PEND_RELEASE'].includes(scope.row.status)" type="text" class="text-btn-cursor" size="small" @click="edit(scope.row)">编辑</el-button>
              <el-button v-if="['REJECTED'].includes(scope.row.status)" type="text" class="text-btn-cursor" size="small" @click="edit(scope.row)">重新编辑</el-button>
              <el-button v-if="['PEND_RELEASE'].includes(scope.row.status)" type="text" class="text-btn-cursor" size="small" @click="exam(scope.row)">提交审核</el-button>
              <el-button v-if="['REJECTED'].includes(scope.row.status)" type="text" class="text-btn-cursor" size="small" @click="exam(scope.row)">再次提交审核</el-button>
              <el-button v-if="['PEND_RELEASE'].includes(scope.row.status)" type="text" class="text-btn-cursor cursor-delete" size="small" @click="handleDelete(scope.row.productionInventoryId)">删除</el-button>
              <el-button v-if="['REJECTED'].includes(scope.row.status)" type="text" class="text-btn-cursor cursor-delete" size="small" @click="showAbort(scope.row)">驳回原因</el-button>
            </template>
          </el-table-column>
        </tdtable>
      </template>
    </BaseMainSlot>
    <AddEditDialog v-model="addEditShow" :show-type="showType" :manufacturing-list="manufacturingList" :selected-item="selectedItem" :task-list="taskList" :product-list="productList" :batch-list="batchList" :type="type" @reflash="search" />
    <el-dialog title="驳回原因" :visible.sync="showAbortDialog" top="0" :close-on-click-modal="false" @close="showAbortDialog = false">
      <p v-if="selectedItem != null">{{ selectedItem.reason || '' }}</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" class="savebtn" @click="showAbortDialog = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import BaseMainSlot from '@/components/BaseMainSlot/newBaseMainSlot';
import SearchForm from '@/components/searchForm';
import apiProduct from '@/api/processing-management/basic-info-manage/product-process';
import api from '@/api/processing-management/process-inventory-manage/index';
import apiTask from '@/api/processing-management/process-task-manage/index';
import AddEditDialog from './components/add-edit-dialog.vue';
import tdtable from '@/components/table/index.vue';
import apiBatch from '@/api/processing-management/process-batch-manage/process-batch-creation/index';
import entrustedApi from '@/api/processing-management/basic-info-manage/entrusted-processing-unit-manage/index';
import { getToken } from '@/utils/auth';
export default {
  inject: ['reload'],
  components: {
    BaseMainSlot,
    SearchForm,
    tdtable,
    AddEditDialog
  },
  props: {
    type: {
      type: String,
      default: 'MATERIAL_REQUISITION'
    }
  },
  data() {
    return {
      showType: 'addEdit',
      manufacturingList: [],
      statusMap: {
        PEND_RELEASE: '待出库',
        REVIEW: '审核中',
        ALREADY_RELEASED: '已出库',
        REJECTED: '已驳回'
      },
      tableData: [],
      tableLoading: false,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      formConfig: [
        {
          label: '创建时间',
          prop: 'date',
          type: 'daterange'
        },
        {
          label: '领料单号',
          prop: 'productionInventoryNo',
          type: 'input'
        },
        {
          label: '工单名称',
          prop: 'taskName',
          type: 'input'
        },
        {
          label: '批次编号',
          prop: 'batchNo',
          type: 'input'
        },
        {
          label: '出库单号',
          prop: 'orderNo',
          type: 'input'
        },
        {
          label: '产品名称',
          prop: 'productId',
          type: 'select',
          options: [],
          optionKey: { label: 'productName', value: 'productId' }
        }
      ],
      filterData: {},
      addEditShow: false,
      selectedList: [],
      delActive: false,
      selectedItem: null,
      productList: [],
      showProcess: false,
      selectedProductItem: null,
      taskList: [],
      batchList: [],
      showAbortDialog: false
    };
  },
  computed: {
    productionInventoryNoLabel() {
      let label = '';
      const { type } = this;
      if (type === 'MATERIAL_REQUISITION') {
        label = '领料单号';
      }
      if (type === 'RECEIPT_ORDER') {
        label = '产品入库单号';
      }
      if (type === 'RETURN_ORDER') {
        label = '原料退库单号';
      }
      return label;
    },
    orderNoLabel() {
      let label = '';
      const { type } = this;
      if (type === 'MATERIAL_REQUISITION') {
        label = '关联出库单号';
      }
      if (type === 'RECEIPT_ORDER') {
        label = '关联入库单号';
      }
      if (type === 'RETURN_ORDER') {
        label = '关联入库单号';
      }
      return label;
    }
  },
  watch: {
    addEditShow(v) {
      if (!v) {
        setTimeout(() => {
          this.selectedItem = null;
          this.showType = 'addEdit';
        }, 250);
      }
    },
    showAbortDialog(v) {
      if (!v) {
        setTimeout(() => {
          this.selectedItem = null;
          this.showType = 'addEdit';
        }, 250);
      }
    }
  },
  created() {
    const { type } = this;
    if (type === 'RECEIPT_ORDER') {
      this.formConfig[1].label = '产品入库单号';
      this.formConfig[4].label = '入库单号';
      this.statusMap.PEND_RELEASE = '待入库';
      this.statusMap.ALREADY_RELEASED = '已入库';
    }
    if (type === 'RETURN_ORDER') {
      this.formConfig[1].label = '原料退库单号';
      this.formConfig[4].label = '入库单号';
      this.statusMap.PEND_RELEASE = '待入库';
      this.statusMap.ALREADY_RELEASED = '已入库';
    }
    this.loadData().then(() => {
      this.search();
    });
  },

  mounted() {},
  methods: {
    loadData() {
      this.tableLoading = true;
      return Promise.all([this.getProductList(), this.getTaskList(), this.getBatchList(), this.getManufacturing()]);
    },
    getManufacturing() {
      return entrustedApi.queryByConditionList({}).then(res => {
        if (res.code === 1) {
          this.manufacturingList = res.data;
        }
      });
    },
    getBatchList() {
      return apiBatch.queryByCondition({}).then(res => {
        if (res.code === 1) {
          this.batchList = res.data;
        }
      });
    },
    getProductList() {
      return apiProduct.queryByCondition({ status: 1 }).then(res => {
        if (res.code === 1) {
          this.productList = res.data;
          this.formConfig.find(i => i.prop === 'productId').options = res.data;
        }
      });
    },
    getTaskList() {
      return apiTask.getTaskList({}).then(res => {
        if (res.code === 1) {
          this.taskList = res.data;
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedList = list.map(item => {
        return item.productionInventoryId;
      });
      if (this.selectedList && this.selectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    handleSizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.search();
    },
    handleCurrentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.search();
    },
    search() {
      const { currentPage, pageSize } = this.page;
      const filterData = JSON.parse(JSON.stringify(this.filterData));
      if (filterData.date && filterData.date.length !== 0) {
        filterData.startTime = this.$moment(filterData.date[0]).format('YYYY-MM-DD HH:mm:ss');
        filterData.endTime = this.$moment(filterData.date[1]).format('YYYY-MM-DD HH:mm:ss');
      }
      delete filterData.date;
      this.tableLoading = true;
      api
        .productionInventory({
          page: currentPage,
          size: pageSize,
          entity: {
            type: this.type,
            ...filterData
          }
        })
        .then(res => {
          if (res.code === 1) {
            this.tableData = this.$utils.addblankmet(res.data.content, pageSize).map(i => {
              return {
                ...i,
                generationTime: i.generationTime ? this.$moment(i.generationTime).format('YYYY-MM-DD HH:mm:ss') : ''
              };
            });
            this.page.total = res.data.totalElements;
            if (res.data.content.length === 0 && this.page.currentPage !== 1) {
              this.page.currentPage--;
              this.search();
            }
          }
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    edit(item, type = 'addEdit') {
      this.showType = type;
      this.selectedItem = JSON.parse(JSON.stringify(item));
      this.addEditShow = true;
    },
    del() {
      this.handleDelete(this.selectedList);
    },
    handleDelete(no) {
      let list = [no];
      if (no instanceof Array) {
        list = no;
      }
      this.$confirm('是否确认删除？', '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '删除',
        cancelButtonText: '取消'
      })
        .then(() => {
          api.del({ productionInventoryIdList: list }).then(res => {
            if (res.code === 1) {
              this.$message.success('删除成功');
              this.search();
            } else {
              this.$message.error('删除失败');
            }
          });
        })
        .catch(_ => {});
    },
    updateSelectedItem(item) {
      this.selectedItem = item;
    },
    showMaterial(row) {
      this.materialList = row.taskRawMaterialList;
      this.showMaterialList = true;
    },
    queryBomByProduct(row) {
      const { processingVolume, productId } = row;
      if (processingVolume && productId) {
        api.queryBomByProduct(processingVolume, productId).then(res => {
          if (res.code === 1) {
            this.materialList = res.data;
          }
        });
      }
    },
    showEqu(item) {
      this.currentDataEquList = item.equipmentList;
      this.showEquDialog = true;
    },
    showSop(item) {
      this.selectedProductItem = item.product;
      this.showProcess = true;
    },
    getProcess(productId) {
      this.processLoading = true;
      apiProduct
        .getProcessesListByCond({
          productId
        })
        .then(res => {
          if (res.code === 1) {
            this.processList = res.data;
          }
        })
        .finally(() => {
          this.processLoading = false;
        });
    },
    exam(row) {
      const { type } = this;
      let text = '提交后会根据领料单信息自动生成出库单，递交给仓储人员进行审核出库，确定要提交吗？';
      if (type === 'RECEIPT_ORDER') {
        text = '提交后会根据产品入库单信息自动生成入库单，递交给仓储人员进行审核入库，确定要提交吗？';
      }
      if (type === 'RETURN_ORDER') {
        text = '提交后会根据原料退库单信息自动生成入库单，递交给仓储人员进行审核入库，确定要提交吗？';
      }
      this.$confirm(text, '提示', {
        distinguishCancelAndClose: true,
        confirmButtonClass: 'btnFalses',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          api
            .submitReview({
              productionInventoryId: row.productionInventoryId,
              name: getToken('username'),
              personNo: getToken('personNo')
            })
            .then(res => {
              if (res.code === 1) {
                this.$message.success('提交成功');
                this.search();
              }
            });
        })
        .catch(_ => {});
    },
    showAbort(row) {
      this.selectedItem = JSON.parse(JSON.stringify(row));
      this.showAbortDialog = true;
    }
  }
};
</script>
<style lang="scss" scoped>
.content-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
}
.PEND_RELEASE {
  color: #fff;
}
.REVIEW {
  color: #e6a23c;
}
.ALREADY_RELEASED {
  color: #67c23a;
}
.REJECTED {
  color: #f56c6c;
}
</style>
